package com.shiguiwu.springboot3.util;

/**
 * @description: 结果
 * @author: stone
 * @date: Created by 2023/7/2 20:54
 * @version: 1.0.0
 * @pakeage: com.shiguiwu.springboot3.util
 */
import com.shiguiwu.springboot3.api.IErrorCode;
import com.shiguiwu.springboot3.enums.ApiErrorCode;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;

import java.io.Serial;
import java.io.Serializable;
import java.util.Objects;
import java.util.Optional;
@Schema(description = "统一api封装返回实体")
@Data
public class R<T> implements Serializable {
    @Serial
    private static final long serialVersionUID = 1L;
    @Schema(description = "api返回编码：0是成功，其他失败", example = "0")
    private Integer code;
    @Schema(description = "api返回数据", example = "User")
    private T data;
    @Schema(description = "api返回消息", example = "保存成功")
    private String msg;

    private R() {
    }


    private R(IErrorCode errorCode) {
        errorCode = (IErrorCode) Optional.ofNullable(errorCode).orElse(ApiErrorCode.FAILED);
        this.code = errorCode.getCode();
        this.msg = errorCode.getMsg();
    }

    public static <T> R<T> ok(T data) {
        ApiErrorCode aec = ApiErrorCode.SUCCESS;
        if (data instanceof Boolean && Boolean.FALSE.equals(data)) {
            aec = ApiErrorCode.FAILED;
        }

        return restResult(data, aec);
    }

    public static <T> R<T> failed(String msg) {
        return restResult(null, ApiErrorCode.FAILED.getCode(), msg);
    }

    public static <T> R<T> failed(IErrorCode errorCode) {
        return restResult(null, errorCode);
    }

    public static <T> R<T> restResult(T data, IErrorCode errorCode) {
        return restResult(data, errorCode.getCode(), errorCode.getMsg());
    }

    private static <T> R<T> restResult(T data, Integer code, String msg) {
        R<T> apiResult = new R<>();
        apiResult.setCode(code);
        apiResult.setData(data);
        apiResult.setMsg(msg);
        return apiResult;
    }

    public boolean ok() {
        return Objects.equals(ApiErrorCode.SUCCESS.getCode(), this.code);
    }


}

